<?php
/**
 * Created by PhpStorm.
 * User: dreamy
 * Date: 2021-12-22
 * Time: 15:16
 */
namespace common\services;

use common\models\StockBalanceHouse;
use common\models\StockWarehouse;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\data\Pagination;

/**
 * Class TallyStockWarehouseService
 * @package common\services
 * 库存（进销存）
 */
class TallyStockWarehouseService extends BaseService
{
    /**
     * 缓存存储KEY
     */
    const CACHE_BUCKET = 'TallyStockWareHouse:';

    /**
     * 缓存有效期
     */
    const CACHE_TIMEOUT = 300; // 5min

    /**
     * 获取某账套下的产品数据 最多100条 有缓存机制
     * @param $tallyId
     *
     * @return array|mixed|\yii\db\ActiveRecord[]
     * @throws
     */
    public static function getAll($tallyId)
    {
        $cacheKey = self::CACHE_BUCKET.$tallyId;

        // 先从缓存里尝试命中
        $redis = Yii::$app->get('redis');
        $cacheData = $redis->get($cacheKey);
        if(!empty($cacheData)) {
            $cacheData = json_decode($cacheData,true);
            return $cacheData ;
        }

        // 查表获取
        $list = StockWarehouse::find()->where([
            'tally_id'   => $tallyId,
            'state'=> StockWarehouse::STATE_VALID
        ])->limit(100)->asArray()->all();

        if(!empty($list)) {
            // 写入缓存
            $redis->setex($cacheKey,self::CACHE_TIMEOUT,json_encode($list,JSON_UNESCAPED_UNICODE));
        }
        return $list ;
    }

    /**
     * 清除对应cache
     * @param $tallyId
     *
     * @throws \yii\base\InvalidConfigException
     */
    public static function clearCache($tallyId)
    {
        $cacheKey = self::CACHE_BUCKET.$tallyId;
        $redis = Yii::$app->get('redis');
        $redis->expire($cacheKey,0);
    }

    /**
     * 某仓库下取出库存>0的前100产品
     * @param $tallyId
     * @param $houseId
     *
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getProductAll($tallyId,$houseId)
    {
        $list = StockBalanceHouse::find()->select('product_id as id,house_id,product_title as title,pure_num')->where([
            'tally_id'   => $tallyId,
            'house_id'   => $houseId
        ])->andFilterWhere(['>','pure_num',0])->limit(100)->asArray()->all();

        return $list ;
    }

    /**
     * 某仓库下符合关键词筛选的分页数据
     * @param       $tallyId
     * @param       $houseId
     * @param array $condition
     *
     * @return array
     */
    public static function getProductSearch($tallyId,$houseId,$condition=[])
    {
        $where = [
            'tally_id' => $tallyId,
            'house_id' => $houseId,
        ];
        $query = StockBalanceHouse::find()
            ->select('product_id as id,house_id,product_title as title,pure_num')
            ->where($where);

        // 其他条件 的筛选器拼接 如关键词（这里只用来搜索标题）
        $keywords = ArrayHelper::getValue($condition,'keywords','');

        if($keywords){
            $keywords = urldecode($keywords);
            $query->andFilterWhere(['like','product_title',$keywords]);
        }

        // 分页相关
        $count = $query->count();
        // 构造分页对象
        $pageSize = $_SERVER['PAGE_SIZE'] ?: 10 ;
        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $count
        ]);
        $pagination->validatePage=false;

        // 从DB获取
        $houseList = $query->orderBy('id desc')
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->asArray()
            ->all();

        // 返回带分页数据
        return [
            'data'       => $houseList ?: [],
            'pageInfo'   => [
                'totalCount' => intval($count) ,
                'pageSize'   => intval($pageSize)
            ]
        ];
    }


    /**
     * 获取某个账套下的仓库列表
     * @param       $tallyId
     * @param array $condition
     *
     * @return array
     */
    public static function getList($tallyId,$condition=[])
    {
        $where = [
            'tally_id' => $tallyId,
        ];
        $query = StockWarehouse::find()->where($where);

        // 其他条件 的筛选器拼接 如关键词（这里只用来搜索标题）
        $keywords = ArrayHelper::getValue($condition,'keywords','');

        if($keywords){
            $keywords = urldecode($keywords);
            $query->andFilterWhere(['like','title',$keywords]);
        }

        // 分页相关
        $count = $query->count();
        // 构造分页对象
        $pageSize = $_SERVER['PAGE_SIZE'] ?: 10 ;
        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $count
        ]);
        $pagination->validatePage=false;

        // 从DB获取
        $houseList = $query->orderBy('id desc')
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->asArray()
            ->all();

        // 返回带分页数据
        return [
            'data'       => $houseList ?: [],
            'pageInfo'   => [
                'totalCount' => intval($count) ,
                'pageSize'   => intval($pageSize)
            ]
        ];
    }

    /**
     * 获取单个仓库信息
     * @param $productId
     * @param $tallyId
     *
     * @return array
     */
    public static function getInfoById($productId,$tallyId)
    {
        $where = [
            'id'    => $productId,
            'tallyId' => $tallyId
        ];

        $info = StockWarehouse::find()
            ->select('*')
            ->where($where)
            ->asArray()
            ->limit(1)
            ->one();
        return $info ?: [];
    }

    /**
     * 添加仓库
     * @param $formData
     * @return bool
     */
    public static function create($formData)
    {
        $model = new StockWarehouse();
        $model->load($formData,'');
        if ($model->validate() && $model->save()) {
            return $model->id ;
        }else{
            Yii::error('StockWarehouse insert error:'.current($model->getFirstErrors()).';post:'.Json::encode($formData,JSON_UNESCAPED_UNICODE));
            self::setError(current($model->getFirstErrors()));
            return false;
        }
    }

    /**
     * 更新单个仓库
     * @param $condition
     * @param $formData
     * @return bool
     */
    public static function update($condition,$formData)
    {
        $model = StockWarehouse::find()->where($condition)->one();
        if(!$model){
            self::setError('仓库不存在');
            return false ;
        }
        $model->load($formData,'');
        if ($model->validate() && $model->save()) {
            return true ;
        }else{
            Yii::error('StockWarehouse update error:'.current($model->getFirstErrors()).';post:'.Json::encode($formData,JSON_UNESCAPED_UNICODE));
            self::setError(current($model->getFirstErrors()));
            return false;
        }
    }

    /**
     * 仓库删除
     * @param $condition
     * @return bool
     * @throws
     */
    public static function delete($condition)
    {
        $model = StockWarehouse::find()->where($condition)->one();
        if(!$model){
            self::setError('产品不存在');
            return false ;
        }
        // 检测是否存在相关的库存产品 如果有不能删除
        $sum = StockBalanceHouse::find()->where([
            'tally_id' => $condition['tally_id'],
            'house_id' => $condition['id']
        ])->sum('pure_num');
        if($sum > 0) {
            self::setError('该仓库下还存在产品，请先清空仓库再进行删除');
            return false;
        }
        if ($model->delete()) {
            return true ;
        }else{
            self::setError(current($model->getFirstErrors()));
            return false;
        }
    }

}
